﻿

#region Usings

#endregion

namespace LongNet.Util.DataTypes
{
    /// <summary>
    /// Helper class that implements a priority queue
    /// </summary>
    /// <typeparam name="T">The type of the values placed in the queue</typeparam>
    public class PriorityQueue<T> : ListMapping<int, T>
    {
        #region Constructor

        /// <summary>
        /// Constructor
        /// </summary>
        public PriorityQueue()
            : base()
        {
        }

        #endregion

        #region Public Functions

        /// <summary>
        /// Peek at the next thing in the queue
        /// </summary>
        /// <returns></returns>
        public virtual T Peek()
        {
            if (Items.ContainsKey(HighestKey))
            {
                return Items[HighestKey][0];
            }
            return default(T);
        }

        public override void Add(int Priority, T Value)
        {
            if (Priority > HighestKey)
                HighestKey = Priority;
            base.Add(Priority, Value);
        }

        /// <summary>
        /// Removes an item from the queue and returns it
        /// </summary>
        /// <returns>The next item in the queue</returns>
        public T Remove()
        {
            T ReturnValue = default(T);
            if (Items.ContainsKey(HighestKey) && Items[HighestKey].Count >= 1)
            {
                ReturnValue = Items[HighestKey][0];
                Items[HighestKey].Remove(ReturnValue);
                if (Items[HighestKey].Count == 0)
                {
                    Items.Remove(HighestKey);
                    HighestKey = int.MinValue;
                    foreach (int Key in Items.Keys)
                    {
                        if (Key > HighestKey)
                            HighestKey = Key;
                    }
                }
            }
            return ReturnValue;
        }

        #endregion

        #region Protected Variables

        protected int HighestKey = int.MinValue;

        #endregion
    }
}